<template>
  <div class="table-area">
    <div class="table-tools">
      <slot name="tools"></slot>
    </div>
    <el-table
      :data="tableData"
      stripe style="width: 100%"
      v-loading="tableLoading"
      :max-height="maxHeight"
      @selection-change="handleSelectionChange"
    >
      <el-table-column v-if="showIndex" type="index" label="序号" width="50" />
      <el-table-column v-if="showSelect" type="selection" width="55" />
      <template v-for="item in props.tableColumns" :key="item.prop">
        <el-table-column v-bind="item">
          <template #default="scope" v-if="item.slot">
            <slot :name="item.slot" v-bind="scope"></slot>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <div :style="pagetionStyle">
      <el-pagination
        v-if="!hidePagetion"
        v-model:current-page="pageParams.current"
        v-model:page-size="pageParams.size"
        :page-sizes="sizes"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
const pagetionStyle = {
  marginTop: '12px',
  display: 'flex',
  justifyContent: 'right'
}
const pageParams = ref({
  current: 1,
  size: 10
})
const props = defineProps({
  tableLoading: false,
  maxHeight: {
    type: Number,
    default: 500
  },
  sizes: {
    type: Array,
    default: [10, 30, 50, 100]
  },
  tableData: {
    required: true,
    type: Array
  },
  total: {
    type: Number,
    default: 0
  },
  tableColumns: {
    type: Array,
    required: true
  },
  hidePagetion: {
    type: Boolean,
    default: false
  },
  showSelect: {
    type: Boolean,
    default: false
  },
  showIndex: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits()
function handleSizeChange(val) {
  if (pageParams.value.current * val > props.total) {
    pageParams.value.current = 1
  }
  emit('pagination', pageParams.value)
}

function handleCurrentChange(val) {
  emit('pagination', pageParams.value)
}
function handleSelectionChange(val) {
  emit('selectionChange', val)
}
</script>

<style scoped>
.table-area {
  background: #fff;
  padding: 10px 8px 8px;
  border-radius: 4px;
}
.table-tools {
  display: flex;
  justify-content: flex-start;
  margin-bottom: 8px;
}
</style>